$(document).ready ->
  background = $("body").data("background-image")
  background_tile = $("body").data("background-tile")
  background_blur = $("body").data("background-blur")
  logo = $("body").data("logo-image")
  disqus_shortname = $("body").data("disqus-shortname")

  $("a.logo div").css("background-image", "url(" + (if logo? then logo else "<%= asset_path('almanac/logo.jpg') %>") + ")")

  if background_tile
    $("body.almanac").css("background-image", "url(" + (if background? then background else "<%= asset_path('almanac/background.jpg') %>") + ")")
  else
    image = new Image()
    options = { amount: background_blur }

    image.onload = ->
      Pixastic.process (Pixastic.process image, "blurfast", options), "blur", options
      $.backstretch options.resultCanvas.toDataURL('image/png')

    image.src = if background? then background else "<%= asset_path('almanac/background.jpg') %>"

  $(".custom-upload input[type=file]").change ->
    $("#new_image input[type=submit]").show()
    $(this).next().find("input").val $(this).val()

  $("a.popup").click (e) ->
    e.preventDefault()
    window.open(this.href, "mywindow","width=600,height=300")

  $("a.add-photo").click (e) ->
    e.preventDefault()
    $("#post_body").val($("#post_body").val() + "![](" + $(this).data("image") + ")")

  $(".delete-image").bind ("ajax:success"), ->
    image = $(this).parent().parent()
    image.fadeOut()

  $(".delete-post").bind ("ajax:success"), ->
    post = $(this).parent().parent()
    if post.prev().attr('class') is "head" and post.next().attr('class') is "head"
      post.prev().fadeOut()
    post.fadeOut()

  $('.datepicker').datepicker({ format: 'yyyy-mm-dd' })

  $("#post_title").change (e) ->
    $("#post_slug").val($(this).val().convertToSlug())

  $("pre").addClass("prettyprint")
  prettyPrint()

  if disqus_shortname and $("#disqus_thread").length != 0
    dsq = document.createElement("script")
    dsq.type = "text/javascript"
    dsq.async = true
    dsq.src = "http://" + disqus_shortname + ".disqus.com/embed.js"
    (document.getElementsByTagName("head")[0] or document.getElementsByTagName("body")[0]).appendChild dsq

unless String::convertToSlug?
  String::convertToSlug = ->
    @toLowerCase().replace(/[^\w ]+/g, "").replace RegExp(" +", "g"), "-"